using System;
using System.Collections.Generic;
using System.Web;
using CodeStory.Core.ObjectEntity;

namespace CodeStory.Core
{
	public class UserContext
	{
		private const string datakey = "CodeStory.UserContext.DataKey";

		private static Guid GuestRoleID;

		static UserContext() {
			RoleObject r = RoleObject.ReadFirst("RoleName=@RoleName", "@RoleName", "Guest");
			GuestRoleID = r.RoleID;
		}

		private static UserContext current = null;
		public static UserContext Current {
			get {
				current = HttpContext.Current.Session[datakey] as UserContext;
				if (current == null) {
					current = CreateEmptyUserContext();
					HttpContext.Current.Session[datakey] = current;
				}
				return current;
			}
		}

		private static UserContext CreateEmptyUserContext() {
			UserContext c = new UserContext();
			c.userName = "Guest";
			c.UserID = Guid.Empty;
			return c;
		}

		private string userName = string.Empty;

		public string UserName {
			get { return userName; }
			set { userName = value; }
		}
		private Guid userID = Guid.Empty;

		public Guid UserID {
			get { return userID; }
			set { userID = value; }
		}
		private List<Guid> roles;

		public List<Guid> Roles {
			get {
				if (roles == null) {
					roles = new List<Guid>(8);
					roles.Add(GuestRoleID);
				}
				return roles;
			}
		}

		public bool IsAuthenticated {
			get { return !UserID.Equals(Guid.Empty); }
		}

		public void LoginOff() {
			HttpContext.Current.Session.Remove(datakey);
		}
	}
}